<template>
  <div class="page white-stage">
    <div class="team-main">
      <group class="no-margin"  title="主管">
        <cell v-for="(member, index) in team.team_managers" :key="index" v-if="team.team_managers && team.team_managers.length"  direction="rtl" :title="member.name" >
        </cell>
      </group>

      <group class="no-margin" title="顾问">
        <cell v-for="(member, index) in team.team_members" :key="index" v-if="team.team_members && team.team_members.length"  direction="rtl" :title="member.name" >
          <span class="delete-member" @click="deleteMember(index)">删除</span>
        </cell>
      </group>
      <div class="btn-group">
        <span class="scrm-default-btn small" @click="selectMembers()">新增顾问</span>
      </div>
      </div>
      <x-dialog v-model="this.$store.state.app.dialogShow" >
        <div class="dialog-message">
          {{ this.$store.state.app.dialogMessage }}
        </div>
        <span class="vux-close" @click="hideDialog">知道了</span>
      </x-dialog>
      <confirm v-model="showDeleteConfirm"
          title="温馨提示"
          @on-confirm="onDeleteConfirm">
        <p style="text-align:center;">你确定要删除此成员吗?删除该成员将会释放该成员的客户名单!</p>
      </confirm>

      <deliver-consult
      :members="members"
      :deliverTeamOpts="deliverTeamOpts"
      :isShow="removeDialogShow"
      @on-cancel="onRemoveCancel"
      @on-confirm="onDeleteConfirm"
      height="100%"
      style="background-color:white;" />
    </div>
</template>

<script>
  // import Vue from 'vue'
  // import clientMenu from '../components/client-menu'
  // import {XInput, Group, Selector, Cell, XDialog} from 'vux'
  import XInput from 'vux/src/components/x-input'
  import Group from 'vux/src/components/group'
  import Selector from 'vux/src/components/selector'
  import Cell from 'vux/src/components/cell'
  import XDialog from 'vux/src/components/x-dialog'
  import Confirm from 'vux/src/components/confirm'

  import store from '../store'
  import {showDialog, hideDialog} from '../lib/dialog'
  import Q from 'q'
  import { mapState, mapActions } from 'vuex'

  import DeliverConsult from '../components/deliver-consult'

  export default{
    data () {
      return {
        teamId: '',
        team: {},
        iconType: '',
        teamname: '',
        showDeleteConfirm: false,
        onDeleteConfirm () {},
        team_managers: [],
        team_members: [],
        members: [],
        deliverTeamOpts: [],
        removeParams: {},
        selected_team_managers: [],
        selected_team_members: [],
        selectManagerValue: '选择营销主管',
        selectMembersValue: '请选择营销顾问',
        removeDialogShow: false,
        mkChargerValue: '0',
        counselorValue: '0',
        // clientSourceValue: '',
        // industryValue: '',
        // teamGenderValue: '',

        initialDingManagersIds: [],
        initialDingMembersIds: [],
        initialSelectedTeamManagers: [],
        initialSelectedTeamMembers: [],
        initialTeamMembers: [],
        initialTeamManagers: [],

        marketingChargers: [
        ]
      }
    },
    components: {
      XInput,
      Group,
      Selector,
      Cell,
      XDialog,
      Confirm,
      DeliverConsult
    },
    methods: {
      onRemoveCancel () {
        this.removeDialogShow = false
      },
      hideDialog () {
        // this.$router.back()
        hideDialog()
      },
      refresh (iscroll) {
        console.log('refresh')
      // Refresh current data
      },

      log () {
        console.log('ee')
      },
      load (iscroll) {
        console.log('load')
        // Load new data
      },

      test () {
        console.log('test')
      },
      onBlur () {

      },
      onShow () {
        console.log(arguments)
      },

      saveTeam (data, msg) {
        let that = this
        this.$vux.loading.show({text: 'loading'})
        store.dispatch('saveTeams', {
          ...that.team,
          ...data
        }).then((response) => {
          if (response.data.errcode === 0) {
            showDialog(msg || '保存成功!')
          } else {
            showDialog(response.data.errmsg)
            console.debug('系统出错!请联系管理员', response.data)
          }
          this.removeDialogShow = false
          this.$vux.loading.hide()
        }).catch((error) => {
          console.debug(error, '系统出错!请联系管理员')
          this.$vux.loading.hide()
          this.removeDialogShow = false
        })
        console.log("this.team", JSON.stringify(that.team), that.team.id)
        // let response = {errcode:0};
        //
        // if(response.errcode === 0) {
        //   alert('保存成功!');
        //   this.$router.back();
        // } else {
        //   alert('系统出错!请联系管理员');
        // }
      },
      deleteMember (index) {
        return Q.Promise((resolve, reject) => {
          this.removeDialogShow = true
          this.onDeleteConfirm = resolve
        }).then((data) => {
          console.log(data, 'onDeleteConfirm')
          const members = this.team.team_members.splice(index, 1)
          this.selected_team_members.forEach((elem, index) => {
            if (members && members[0].ding_user_id === elem.emplId) {
              this.selected_team_members.splice(index, 1)
            }
          })
          this.saveTeam(data, '删除成功!')
        })
      },
      clone (obj) {
        return JSON.parse(JSON.stringify(obj))
      },
      unique (array) {
        return array.filter((value, index, self) => { 
          return self.indexOf(value) === index;
        })
      },
      uniqueByKey (list, id) {
        const freshList = {}
        for (const i in list) {
          const item = list[i]
          freshList[item[id]] = item
        }
        return Object.values(freshList)
      },
      resetTeamData () {
        this.$nextTick(() => {
          this.initialTeamManagers = this.clone(this.team.team_managers)
          this.initialSelectedTeamManagers = this.clone(this.selected_team_managers)

          this.initialTeamMembers = this.clone(this.team.team_members)
          this.initialSelectedTeamMembers = this.clone(this.selected_team_members)
        })
      },
      // 编辑初始化选择的主管、成员
      initTeamInfo (id) {
        let that = this
        store.dispatch('getTeam', id)
        .then(function (response) {

          if (response.data.errcode === 0) {
            let team_managers = [];
            let selected_team_managers = [];
            let selected_team_members = [];

            that.team = response.data.results;
            that.team.team_managers
              .forEach(function(element){
              // console.log('element.ding_user_id', element, elemnt.suid, element.ding_user_id)
              selected_team_managers.push({
                emplId: element.ding_user_id || element.suid,
                name : element.name
              })
              });

            that.selected_team_managers = selected_team_managers;
            that.team_managers = that.team.team_managers

            that.team.team_members
              .forEach(function(element){
              // console.log('element.ding_user_id', element, elemnt.suid, element.ding_user_id)
                selected_team_members.push({
                  emplId: element.ding_user_id || element.suid,
                  name : element.name
                })
            });

            that.selected_team_members = selected_team_members;
            that.team_members = that.team.team_members
            that.team.id = id;
            that.members = that.team.team_managers.concat(that.team.team_members)
            that.resetTeamData()
          } else {
            console.debug('系统出错!请联系管理员', response.data);
          }
        }).catch((error) => {
          console.log(error)
        })
      },


      selectManager () {
        console.log('selectManager')
        var that = this;
        let users = [];

        this.selected_team_managers
        .forEach(function(element){
          users.push(element.emplId);
        })


        this.callJsApi('biz.contact.choose',{users: users})
        .then(function(data){
          console.log(JSON.stringify(data));

          var team_managers = [];

          data.forEach(function(object, index){
            team_managers.push({
              ding_user_id : object.emplId,
              name : object.name
            })
          });

          that.team_managers = team_managers;
          that.team.team_managers = team_managers;
          that.selected_team_managers = data;
        });
      },

      selectMembers () {

        var that = this;
        let users = [];

        this.selected_team_members.forEach(function(element){
          users.push(element.emplId)
        })
        console.log('users: ', JSON.stringify(users))

        this.callJsApi('biz.contact.choose',{
          users: users
        }).then(function(data){

          var team_members = [];

          data.forEach(function(object, index) {
            team_members.push({
              ding_user_id : object.emplId,
              name : object.name
            })
          });

          console.log(that, 'team_members');

          const selectedMembers = that.uniqueByKey(that.initialTeamMembers.concat(that.clone(team_members)), 'ding_user_id')
          
          that.team_members = selectedMembers
          that.team.team_members = selectedMembers
          that.selected_team_members = that.uniqueByKey(that.initialSelectedTeamMembers.concat(data), 'emplId');
          that.saveTeam('新增顾问成功!')
        });
      }

    },

    watch:{

      mkChargerValue(value){
        this.team.orderway = value;
      },
      counselorValue(value){
        this.team.counselor = value;
      },
      amountValue(value){
        this.team.amount = value;
      },

      team_members(value) {

        var selectManagerValue = '';
        var isNotElippse = false;

        this.selected_team_members.forEach(function(object, index){
          if(index < 3) {
            selectManagerValue += (index === 0 ? '' : '、')+object.name;
          } else if(isNotElippse === false) {
            selectManagerValue += '...';
            isNotElippse = true;
          }
        });

        this.selectMembersValue = selectManagerValue;
      },

      team_managers(value) {

        var selectManagerValue = '';
        var isNotElippse = false;

        this.selected_team_managers.forEach(function (object, index) {
          if (index < 3) {
            selectManagerValue += (index === 0 ? '' : '、') + object.name
          } else if (isNotElippse === false) {
            selectManagerValue += '...'
            isNotElippse = true
          }
        })

        this.selectManagerValue = selectManagerValue;
      }

    },
    mounted () {
      this.callJsApi('biz.navigation.setTitle', { title: '成员管理' })
      this.teamId = this.$route.query.id
      this.initTeamInfo(this.teamId)
      console.log('edit-team', JSON.stringify(this.team), this.team.id)
      console.log(this.loginUser)
      const myTeamList = this.loginUser.my_team_list
      const myTeamManangeList = this.loginUser.teams
      let deliverTeamOpts = []
      if (! this.loginUser.is_manager) {
        for (const teamId in myTeamManangeList) {
          deliverTeamOpts.push({
            key: myTeamManangeList[teamId].team_id,
            value: myTeamManangeList[teamId].team_name
          })
        }
      } else {
        for (const teamId in myTeamList) {
          deliverTeamOpts.push({
            key: teamId,
            value: myTeamList[teamId]
          })
        }
      }
      this.deliverTeamOpts = deliverTeamOpts
      console.log(this.deliverTeamOpts)
    },
    computed: {
      ...mapState({
        loginUser: state => state.app.user,
        type: state => state.route.name
    })
  }

  }
</script>

<style lang='less'>
  @import "../less/base";

  .team-main{

    .delete-member {
      color: #009DD9;
    }

  .no-margin {
     &>*{
     margin: 0
     }
  }

  .add-new-btn {
    width: 60%;
  }

  .btn-group {
    margin-top: 15px;

    .pull-left{
      float: left;
    }

    .pull-right{
      float: right;
    }
  }

  .delete-tips {
    font-size: 12px;
    text-align: center;
    color:#999999;
    padding: 10px 0;
  }

  }
</style>
